﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;

namespace bmapi.Controllers
{
    [Route("pc")]
    public class PCController : BuyiController
    {
        [HttpPost]
        public HttpResponseMessage ResetPC(dynamic obj)
        {
            User user = GetUserByLoginID(GetCrrentIDByToken());
            if (obj == null)
                return AssistFun.toJson(new { status = 201, tip = "参数不能为空" });
            else
            {
                if(user.power!=1)
                    return AssistFun.toJson(new { status = 201, tip = "仅主管有该权限" });
                #region 参数
                int pcid = Convert.ToInt32(obj.pcid);
                int code = Convert.ToInt32(obj.code);
                #endregion
                SQLCommand sc = null;                
                string sql = "select bind_id from Order_tb where id=@pcid";
                sc = new SQLCommand(sql,"@pcid",pcid);
                string bindid = sc.ExecuteScalar();
                if (Convert.ToInt32(bindid) != 0)
                    pcid = Convert.ToInt32(bindid);
                sql = "select user_id from Task_tb where id=@pcid and code=@code";
                sc = new SQLCommand(sql);
                sc.Add("@pcid",pcid);
                sc.Add("@code",code);
                string userId = sc.ExecuteScalar();
                if (userId == null)
                    return AssistFun.toJson(new { status = 201, tip = "找不到历史执行人，没有操作依据" });
                else
                    return ResetPC(pcid, code, user.PLID);
            }
        }
        /// <summary>
        /// 重置 新增流程 
        /// </summary> 
        /// <param name="pcid"></param>
        /// <param name="code"></param>
        private HttpResponseMessage ResetPC(int pcid, int code,int plid)
        {
            try
            {
                SQLCommand sc = null;
                string sql = "select id,name,o_model_id,rank,bind_id from Order_tb where (id=@pcid or bind_id=@pcid) and o_PLID=@plid and state=2";
                sc = new SQLCommand(sql);
                sc.Add("@pcid", pcid);
                sc.Add("@plid", plid);
                DataTable dt = sc.ExecuteScalars();
                if (dt == null)
                    return AssistFun.toJson(new { status = 201, tip = "找不到已完成订单的相关数据" });
                else
                {
                    sql = "select user_id from Task_tb where id=@pcid and code=@code";
                    sc = new SQLCommand(sql);
                    sc.Add("@pcid", pcid);
                    sc.Add("@code", code);
                    string userId = sc.ExecuteScalar();
                    if (userId == null)
                        return AssistFun.toJson(new { status = 201, tip = "没有找到历史处理用户" });
                    else
                    {
                        sql = "select grouping from User_tb where login_id=@userid";
                        sc = new SQLCommand(sql, "@userid", Convert.ToInt32(userId));
                        int grouping = Convert.ToInt32(sc.ExecuteScalar());
                        //绑定时 添加绑定个数的流程 
                        List<SQLCommand> cmds = new List<SQLCommand>();
                        List<int> pcids = new List<int>();
                        foreach (DataRow dr in dt.Rows)
                        {
                            sql = "insert into PC_tb values(";
                            sc = new SQLCommand();
                            int orderid = Convert.ToInt32(dr["id"]);
                            pcids.Add(orderid);
                            sc.AddInsert("@pcid",orderid );
                            sc.AddInsert("@path", dr["name"].ToString());
                            sc.AddInsert("@plid", plid);
                            sc.AddInsert("@rank", Convert.ToInt32(dr["rank"]));
                            sc.AddInsert("@bind_id", Convert.ToInt32(dr["bind_id"]));
                            sc.AddInsert("@step", code);
                            sc.AddInsert("@station", Convert.ToInt32(userId));
                            sc.AddInsert("@grouping", grouping);
                            sc.AddInsert("@maxstep", code);
                            sc.AddInsert("@download", 1);
                            sc.AddInsert("@model_id", Convert.ToInt32(dr["o_model_id"]));
                            sc.JoinSql(sql);
                            cmds.Add(sc);
                            WriteDebug("sql：", sql);
                        }
                        //绑定时 order_id=bind_id  不绑  order_id=@orderid 
                        sql = "delete from Bed_tb where order_id=@orderid";
                        sc = new SQLCommand(sql, "@orderid", pcid);
                        cmds.Add(sc);
                        int res = SQLCommand.ExecTran(cmds);
                        if (res == 0)
                            return AssistFun.toJson(new { status = 201, tip = "数据操作失败" });
                        else
                        {
                            if (pcids.Count != 0 && pcids.Count == 1)
                                //删除历史文件 修改订单状态 绑定时秩序山粗主订单的历史文件即可
                                return DeleteMaskFile(pcid);
                            else
                            {
                                HttpResponseMessage hm = new HttpResponseMessage();
                                WriteDebug("流程数：", pcids.Count.ToString());
                                for (int i = 0; i < pcids.Count; i++)
                                {                                    
                                    hm = DeleteMaskFile(pcids[i]);
                                }
                                return hm;
                            }

                        }
                    }
                  }
                }
                catch (Exception e)
                {
                    return AssistFun.toJson(new { status = 201, tip = "异常:"+e.Message });
                }
        }

        /// <summary>
        /// 不存在流程 创建流程
        /// </summary> 
        /// <param name="pc"></param>
        /// <param name="code"></param>
        private HttpResponseMessage DeleteMaskFile(int pcid)
        {
            try
            {
                SQLCommand namesc = new SQLCommand("select name from Order_tb where id=@pcid","@pcid",pcid);
                string path = namesc.ExecuteScalar();
                string ncPath = m_buyiRoot + "\\BuyiCut\\" + path;
                if (Directory.Exists(ncPath))
                    DeleteFolder(ncPath);
                string hisOrderPath = GetOrderFile(pcid, null);//历史订单文件
                if (Directory.Exists(hisOrderPath))
                {
                    //移动文件夹  
                    string workPath = m_buyiRoot + "\\buyiWork\\" + path;
                    if (!Directory.Exists(workPath))
                        Directory.CreateDirectory(workPath);
                    WriteDebug("DeleteMaskFile", "path:" + path + "，hisOrderPath:" + hisOrderPath + ",workPath:" + workPath);
                    MoveFolder(hisOrderPath, workPath);
                    //修改订单状态  
                    string sql = "update Order_tb set state=1 where id=@pcid";
                    SQLCommand sc = new SQLCommand(sql, "@pcid", pcid);
                    sc.ExecuteNonQuery();
                }
                else
                {
                    return AssistFun.toJson(new { status = 201, tip = "文件路径不存在" });
                }
                //if (Directory.Exists(hisOrderPath))   
                //{ 
                //    string bomPath = hisOrderPath+ "\\" + path + ".bom";  
                //    if (File.Exists(bomPath))
                //        File.Delete(bomPath);
                //}     
                ////删除plan文件然后历史文件中的订单文件移到流程目录下  
                //string planPath= hisOrderPath + "\\" + path + ".plan";  
                //if (File.Exists(planPath))  
                //    File.Delete(planPath);   
                
            }
            catch (Exception ex)
            {
                return AssistFun.toJson(new { status = 201, tip = "异常 :"+ex.Message });
            }
            return AssistFun.toJson(new { status = 200, tip = "成功" });

        }
       
    }
}
